﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Object = UnityEngine.Object;

public class BodyManager {
	// === Public =====================================================================================================
	public static BodyManager CreateInstance() {
		var instance = new BodyManager();
		return instance;
	}

	public void CreateBody(GameObject ownerParent, FieldBodyType type, Vector3 position = default(Vector3)) {
		CreateGoBody(ownerParent, type, position);
	}

	public void DestroyBodies(List<FieldBody> bodies = null) {
		var list = bodies ?? new List<FieldBody>(GameData.GetInstance.Bodies);
		foreach (var body in list) {
			DestroyBody(body);
		}
	}

	public void DestroyBody(FieldBody body) {
		Object.Destroy(body.GameObject);
		GameData.GetInstance.RemoveBody(body);
	}

	// === Private ====================================================================================================
	private void CreateGoBody(GameObject ownerParent, FieldBodyType type, Vector3 position) {
		var prefab = Tools.Prefab.GetPrefab(type);
		var goBody = Tools.Prefab.Create<GameObject>(prefab);
		if (ownerParent != null) {
			goBody.transform.parent = ownerParent.transform;
		}
		var bodyData = GetBodyData(type, position);
		goBody.transform.position = bodyData.CurPoint;
		goBody.transform.LookAt(bodyData.NextPoint);
		var body = new FieldBody {
			FieldBodyType = type,
			GameObject = goBody,
			BodyData = bodyData,
		};
		GameData.GetInstance.AddBody(body);
	}

	private BodyData GetBodyData(FieldBodyType type, Vector2 position) {
		BodyData data;
		if (type.Equals(FieldBodyType.Head)) {
			data = new BodyData(position, Vector3.right);
			data.StartMove();
		} else {
			data = new BodyData(GameData.GetInstance.Bodies.Last().BodyData);
		}
		return data;
	}
}
